package com.gss.security.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.gss.security.domain.UserDetailsDTO;
import com.gss.security.persistence.AuthenticationDAO;

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler{

	AuthenticationDAO authenticationDAO;
	
	private Logger logger = Logger.getLogger(CustomAuthenticationSuccessHandler.class);
	
	
	public AuthenticationDAO getAuthenticationDAO() {
		return authenticationDAO;
	}

	public void setAuthenticationDAO(AuthenticationDAO authenticationDAO) {
		this.authenticationDAO = authenticationDAO;
	}


	public void onAuthenticationSuccess(HttpServletRequest httpservletrequest,
			HttpServletResponse httpservletresponse,
			Authentication authentication) throws IOException,
			ServletException {
		
		UserDetailsDTO requestDTO = (UserDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();	
		if(null != requestDTO.getCount() && requestDTO.getCount() >= 0){
			requestDTO.setCount(1);
			try {
				authenticationDAO.updateUserDetails(requestDTO);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e.getMessage());
			}
		}
	
		if(requestDTO != null){
			if(requestDTO.isCredentialsExpired() == true){
				httpservletresponse.sendRedirect("changepasswd.htm");
			}
			else{
				httpservletresponse.sendRedirect("authenticate.htm");
			}
		}
		
	}
}


